package com.glory.brepda.activity.technicalservice;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.EqpKeepCheckListAdapter;
import com.glory.brepda.adapter.EqpKeepInputListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.EDCListBean;
import com.glory.brepda.entity.EqpKeepBean;
import com.glory.brepda.entity.EqpKeepInputListBean;
import com.glory.brepda.entity.EqpKeepSelectorListBean;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_InitUtils;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class Eqp_EqpKeepDetailsActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.rvKeepCheckList)
    RecyclerView rvKeepCheckList;
    @BindView(R.id.rvKeepInputList)
    RecyclerView rvKeepInputList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    @BindView(R.id.tvReplay_QC)
    TextView tvReplay_QC;
    @BindView(R.id.llCheckLayout)
    LinearLayout llCheckLayout;
    @BindView(R.id.llInputLayout)
    LinearLayout llInputLayout;
    @BindView(R.id.tvSave)
    TextView tvSave;
    @BindView(R.id.flSpecialList)
    FrameLayout flSpecialList;
    @BindView(R.id.tvSpecial)
    TextView tvSpecial;
    @BindView(R.id.ivReasonArrow)
    ImageView ivReasonArrow;
    private String scheduleRrn;
    private EqpKeepCheckListAdapter eqpKeepCheckListAdapter;
    private EqpKeepInputListAdapter eqpKeepInputListAdapter;
    private List<EqpKeepSelectorListBean> checkTableLineDatas;
    private String eqpWork;
    private FreeUI_GeneralPop mReasonPop;
    private List<String> mReasonList =new ArrayList<>(Arrays.asList("","A.待料","B.放假","C.维修","/"));
    private int currentUploadPosition = -1;
    private String mFilePath = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_eqp_keep_detials;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        scheduleRrn = bundle.getString("scheduleRrn");
        eqpWork = bundle.getString("eqpWork");

        rvKeepCheckList.setLayoutManager(new LinearLayoutManager(Eqp_EqpKeepDetailsActivity.this));
        rvKeepCheckList.setItemAnimator(new DefaultItemAnimator());
        rvKeepCheckList.addItemDecoration(new DividerItemDecoration(Eqp_EqpKeepDetailsActivity.this, 1));
        eqpKeepCheckListAdapter = new EqpKeepCheckListAdapter(null, new EqpKeepCheckListAdapter.OnUploadClickListener() {
            @Override
            public void onUploadClick(int position) {
                currentUploadPosition = position;
                mFilePath = Environment.getExternalStorageDirectory().getPath() + "/mytest.png";
                Uri mUri = Uri.fromFile(new File(mFilePath));
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                startActivityForResult(openCameraIntent, 1);
            }
        });
        eqpKeepCheckListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        eqpKeepCheckListAdapter.isFirstOnly(true);
        rvKeepCheckList.setAdapter(eqpKeepCheckListAdapter);

        rvKeepInputList.setLayoutManager(new LinearLayoutManager(Eqp_EqpKeepDetailsActivity.this));
        rvKeepInputList.setItemAnimator(new DefaultItemAnimator());
        rvKeepInputList.addItemDecoration(new DividerItemDecoration(Eqp_EqpKeepDetailsActivity.this, 1));
        eqpKeepInputListAdapter = new EqpKeepInputListAdapter(null, new EqpKeepInputListAdapter.OnUploadClickListener() {
            @Override
            public void onUploadClick(int position) {
                currentUploadPosition = position;
                mFilePath = Environment.getExternalStorageDirectory().getPath() + "/mytest.png";
                Uri mUri = Uri.fromFile(new File(mFilePath));
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                startActivityForResult(openCameraIntent, 2);
            }
        });
        eqpKeepInputListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        eqpKeepInputListAdapter.isFirstOnly(true);
        rvKeepInputList.setAdapter(eqpKeepInputListAdapter);
        tvSpecial.setText("");

        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        eqpKeepCheckListAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void initData() {

        FreeUI_EntityCallBack<BaseResponseBean<EqpKeepBean>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpKeepBean>>
                (new TypeToken<BaseResponseBean<EqpKeepBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onSuccess(Response<BaseResponseBean<EqpKeepBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    EqpKeepBean eqpKeepBean = response.body().getResponse().getBody();
                    if (eqpKeepBean.getCheckTableLineDatas().size() > 0) {
                        llCheckLayout.setVisibility(View.VISIBLE);
                        checkTableLineDatas = eqpKeepBean.getCheckTableLineDatas();
                        eqpKeepCheckListAdapter.setNewData(checkTableLineDatas);
                    }

                    if (eqpKeepBean.getLineDatas().size() > 0) {
                        llInputLayout.setVisibility(View.VISIBLE);
                        //代码逻辑影响保养值比对，故注释
//                        eqpKeepBean.getLineDatas().forEach(new Consumer<EqpKeepInputListBean>() {
//                            @Override
//                            public void accept(EqpKeepInputListBean eqpKeepInputListBean) {
//                                eqpKeepInputListBean.setConstantValue("0");
//                            }
//                        });
                        eqpKeepInputListAdapter.setNewData(eqpKeepBean.getLineDatas());
                    }
                    putPmsScheduleResults(eqpKeepBean);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EqpKeepBean>> response) {
                super.onError(response);
                loadError(response.getException(), "PMSSCHEDULE");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "queryScheduleForm");
        map.addProperty("scheduleRrn", scheduleRrn);
        NetUtils.requestPostNet("IF.PMSSCHEDULE", "PMSSCHEDULE", Eqp_EqpKeepDetailsActivity.this, map, callBack);

    }

    private void putPmsScheduleResults(EqpKeepBean eqpKeepBean) {
        ArrayList<String> udfList = new ArrayList<>();
        for (EqpKeepInputListBean udf:eqpKeepBean.getLineDatas()) {
            if (udf.getUDF() != null){
                udfList.add(udf.getUDF().getEapParame());
            }
        }
        FreeUI_EntityCallBack<BaseResponseBean<EDCListBean>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EDCListBean>>
                (new TypeToken<BaseResponseBean<EDCListBean>>() {
                }.getType(),getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EDCListBean>> response) {
                super.onSuccess(response);
                FreeUI_InitUtils.initOkGo(MyApp.getInstance(),30*1000L,0);
                if (response.body().isSuccess(Eqp_EqpKeepDetailsActivity.this, false, getSupportFragmentManager())) {
                    for(EqpKeepInputListBean data : eqpKeepInputListAdapter.getData()){
                        for(EDCListBean.ListBean list : response.body().getResponse().getBody().getList()){
                            if (data.getUDF().getEapParame().equals(list.getName())){
                                data.setDataString(list.getValue());
                            }
                        }
                    }
                    eqpKeepInputListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EDCListBean>> response) {
                super.onError(response);
                FreeUI_InitUtils.initOkGo(MyApp.getInstance(),30*1000L,0);
                FreeApi_ToastUtils.showFreeToast("连接服务器失败", Eqp_EqpKeepDetailsActivity.this, false, 0);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("eqpId", eqpWork);
        map.add("eapParame", new JsonParser().parse(new Gson().toJson(udfList)));
        //FreeUI_InitUtils.initOkGo(MyApp.getInstance(),80*1000L,0);
        NetUtils.requestPostNet("IF.EDCPARAME", "EDCPARAME", Eqp_EqpKeepDetailsActivity.this, map, callBack);

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("设备保养");
        freeUI_titleView.setRightListener(R.drawable.selector_refresh, v -> {
            eqpKeepCheckListAdapter.getData().clear();
            eqpKeepCheckListAdapter.notifyDataSetChanged();
            eqpKeepInputListAdapter.getData().clear();
            eqpKeepInputListAdapter.notifyDataSetChanged();
            eqpKeepInputListAdapter.clearData();
            initData();
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.tvReplay, R.id.tvSave, R.id.tvReplay_QC,R.id.flSpecialList})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvSave:
                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {
                        submit("false","");
                    }
                },"临时保存确认？");
                break;
            case R.id.tvReplay:
                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {

                        if (!tvSpecial.getText().equals("")){
                            submit("true","");
                            return;
                        }

//                        if (eqpKeepInputListAdapter.getOutData().size() > 0) {
//                            showConfirmDialog("数值已超限");
//                            return;
//                        }



                        List<EqpKeepSelectorListBean> data = eqpKeepCheckListAdapter.getData();
                        for (EqpKeepSelectorListBean bean : data) {
                            if (FreeApi_StringUtils.isEmpty(bean.getReserved1())) {
                                showToast("保养状态项不能为空", false);
                                return;
                            }

                            if (FreeApi_StringUtils.isEmpty(bean.getReserved9()) && bean.getReserved10().length() > 0 && !bean.getReserved10().contains(";")) {
                                showToast("QC采集项未完成", false);
                                return;
                            }
                        }
                        submit("true","");
                    }
                },"确认提交？");
                break;
            case R.id.tvReplay_QC:
                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {
//                        if (eqpKeepInputListAdapter.getOutData().size() > 0) {
//                            showConfirmDialog("数值已超限");
//                            return;
//                        }

                        List<EqpKeepSelectorListBean> data = eqpKeepCheckListAdapter.getData();
                        for (EqpKeepSelectorListBean bean : data) {
                            if (FreeApi_StringUtils.isEmpty(bean.getReserved1())) {
                                showToast("保养状态项不能为空", false);
                                return;
                            }

                            if (FreeApi_StringUtils.isEmpty(bean.getReserved9()) && bean.getReserved10().length() > 0 && !bean.getReserved10().contains(";")) {
                                showToast("QC采集项未完成", false);
                                return;
                            }
                        }
                        submit("true","QC");
                    }
                },"确认提交？");
                break;
            case R.id.flSpecialList:
                if (mReasonPop != null) {
                    if (mReasonPop.isShowing()) {
                        mReasonPop.dismiss();
                    }
                } else {
                    mReasonPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flSpecialList.getWidth(), mReasonList, ivReasonArrow, (codeS, i) -> {
                        tvSpecial.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivReasonArrow);
                mReasonPop.showAsDropDown(flSpecialList, 0, 0);
                break;
        }

    }

    private void submit(String isFinished,String qc) {

        FreeUI_EntityCallBack<BaseResponseBean<EqpKeepBean>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpKeepBean>>
                (new TypeToken<BaseResponseBean<EqpKeepBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EqpKeepBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    showConfirmDialog(Eqp_EqpKeepDetailsActivity.this, isFinished.equals("true") ? "保存成功" : "临时保存成功");
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EqpKeepBean>> response) {
                super.onError(response);
                loadError(response.getException(), "PMSSCHEDULE");
            }
        };

        JsonObject map = new JsonObject();
//        JsonObject checkJson = new JsonObject();
//        checkJson.add("XPdaPmsSheetCheckTableLineData", new JsonParser().parse(new Gson().toJson(eqpKeepCheckListAdapter.getData())).getAsJsonArray());
//        JsonObject inputJson = new JsonObject();
//        inputJson.add("XPdaPmsDatasLineData", new JsonParser().parse(new Gson().toJson(eqpKeepInputListAdapter.getData())).getAsJsonArray());
        map.addProperty("actionType", "saveScheduleForm");
        map.addProperty("isFinished", isFinished);
        map.addProperty("QC",qc.equals("")?"":"PM_QC");
        map.addProperty("RESERVED8",tvSpecial.getText().toString());
        map.add("XPdaPmsDatasLineDatas", new JsonParser().parse(new Gson().toJson(eqpKeepInputListAdapter.getData())).getAsJsonArray());
        map.add("XPdaPmsSheetCheckTableLineDatas", new JsonParser().parse(new Gson().toJson(eqpKeepCheckListAdapter.getData())));
        map.addProperty("scheduleRrn", scheduleRrn);

        NetUtils.requestPostNet("IF.PMSSCHEDULE", "PMSSCHEDULE", Eqp_EqpKeepDetailsActivity.this, map, callBack);

    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        EqpKeepSelectorListBean item = checkTableLineDatas.get(position);
//        if (item.getReserved10().length() > 0 && !item.getReserved10().contains(";") && !item.getReserved9().equals("Y")) {
//            if (actionControl("Work_DataCollectActivity", "PDAWorkFragment", "无一般数据采集权限")) {
//                return;
//            }
//            Intent intent = new Intent(this, Work_DataCollectActivity.class);
//            intent.putExtra("position", String.valueOf(position));
//            intent.putExtra("eqpWork", eqpWork);
//            intent.putExtra("paramList", item.getReserved10());
//            startActivityForResult(intent, 500);
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 500) {
                if (data != null) {
                    int position = Integer.parseInt(data.getStringExtra("position"));
                    if (position >= 0) {
                        checkTableLineDatas.get(position).setReserved9("Y");
                        eqpKeepCheckListAdapter.notifyItemChanged(position);
                    } else {
                        showConfirmDialog("数据采集填写错误");
                    }

                }
            }
            if (requestCode == 1 || requestCode == 2){
                Uri uri1 = Uri.fromFile(new File(mFilePath));
                ContentResolver cr = this.getContentResolver();
                try {
                    InputStream is = cr.openInputStream(uri1);
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 3;
                    Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
                    String imageData = bitmapToBase64(bitmap);

                    if (!imageData.equals("")) {
                        if (requestCode == 1) {
                            eqpKeepCheckListAdapter.getData().get(currentUploadPosition).setReserved7(imageData);
                            rvKeepCheckList.post(() -> {
                                eqpKeepCheckListAdapter.notifyItemChanged(currentUploadPosition);
                            });
//                        mCheckAdapter.notifyItemChanged(currentUploadPosition);
                        } else{
                            eqpKeepInputListAdapter.getData().get(currentUploadPosition).setImageUrl(imageData);
                            rvKeepInputList.post(() -> {
                                eqpKeepInputListAdapter.notifyItemChanged(currentUploadPosition);
                            });
//                        mMeasurementAdapter.notifyItemChanged(currentUploadPosition);
                        }
                    } else {
                        showToast("图片加载失败", false);
                    }
                } catch (Exception e) {
                    Log.i("upImage", e.toString());
                }
            }
        }
    }

    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


}
